package com.hyd.tweet.twitter;

import com.hyd.tweet.AppException;
import com.hyd.tweet.Application;
import com.hyd.tweet.twitter.command.Command;
import com.hyd.tweet.user.User;
import com.hyd.tweet.user.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.TwitterException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yiding.he
 */
public class CommandProcessor {

    static final Logger log = LoggerFactory.getLogger(CommandProcessor.class);

    public CommandProcessor() {
    }

    public static List<String> process(String cmd, User user) {
        List<String> result = new ArrayList<String>();

        Command command = Command.getCommand(cmd);
        try {

            if (command != null) {
                result = new ArrayList<String>(command.process(cmd, user));
            } else {
                result = new ArrayList<String>(Arrays.asList("未知命令: " + cmd));
            }

        } catch (Exception e) {
            if (e instanceof AppException &&
                    e.getCause() instanceof TwitterException &&
                    ((TwitterException) e.getCause()).getStatusCode() == 401) {
                log.error("用户 " + user.getAccount() + " 的授权信息不再有效，已删除。", e);
                UserManager.deleteUser(user.getAccount());
                result.add("——更新失败：您的推特授权已经失效，请通过浏览器翻墙访问 http://"
                        + Application.getAppId() + ".appspot.com 重新授权。");
            }

            if (command != null && command.showErrorsToUser()) {
                result.add("——更新失败：" + e.getMessage());
            }
            log.error("处理来自" + user + "的命令失败", e);
        }

        user.saveToCache();
        return result;
    }
}
